#include "plotview.h"
#include "plotcontroller.h"
#include <QDebug>

PlotView::PlotView(PlotData *data, int w, int h) :
    m_width(w),
    m_height(h),
    plotdata(data),
	m_curveShowWid(NULL)
{
    this->Initialize();
    plotdata->registerObserver(this);
    plotcontroller = new PlotController(plotdata, this);
}

PlotView::~PlotView()
{
}

void PlotView::setWidth(int w)
{
    m_width = w;
    this->setMinimumSize(m_width, m_height);
}

void PlotView::setHeight(int h)
{
    m_height = h;
    this->setMinimumSize(m_width, m_height);
}

int PlotView::getHeight()
{
    return m_height;
}

int PlotView::getWidth()
{
    return m_width;
}

void PlotView::setCurveShowWidget(QWidget *w)
{
	m_curveShowWid = w;
}

QWidget *PlotView::getCurveShowWidget()
{
	return m_curveShowWid;
}

PlotData *PlotView::getPlotData()
{
    return plotdata;
}

void PlotView::setPlotData(PlotData *data)
{
    plotdata = data;
}

void PlotView::Initialize()
{
    m_curveCount = 0;
    this->setMinimumSize(m_width, m_height);
	m_zoomState = false;
}

void PlotView::update()
{
    double **xdata = plotdata->getXData();
    double **ydata = plotdata->getYData();
    int *pos = plotdata->getPos();

    for(int i = 0; i < m_curveCount; i ++){
        curves[i]->setSamples(xdata[i], ydata[i], pos[i]);
    }

    this->replot();
}

// really add curve
void PlotView::addCurve(std::string cur_name)
{
        curves[m_curveCount] = new QwtPlotCurve(QString(cur_name.c_str()));
        curves[m_curveCount]->setRenderHint(QwtPlotItem::RenderAntialiased);
        curves[m_curveCount]->attach(this);
        QwtPlotGrid *grid = new QwtPlotGrid();
        grid->attach(this);
        m_curveCount ++;
}

int PlotView::getCurveId(std::string cur_name)
{
    int i;
    for(i = 0; i < m_curveCount; i ++){
        if(plotdata->getCurveName(i) == cur_name) break;
    }
    if(i >= 0) return i;
    return -1;
}

void PlotView::showCurve(std::string cur_name)
{
    int curId = getCurveId(cur_name);
    if(curId >= 0){
        this->showCurve(curId);
    }
}

void PlotView::hideCurve(std::string cur_name)
{
    int curId = getCurveId(cur_name);
    if(curId >= 0){
        this->hideCurve(curId);
    }
}

void PlotView::showCurve(int cur_id)
{
    curves[cur_id]->attach(this);
    this->replot();
}

void PlotView::hideCurve(int cur_id)
{
    curves[cur_id]->detach();
    this->replot();
}

void PlotView::mouseDoubleClickEvent(QMouseEvent *)
{
	m_zoomState = m_zoomState ? false:true;
	emit zoomStateChanged(m_zoomState);
}

// slots
void PlotView::AddData(double x, double y, int curve)
{
    plotcontroller->addData(x, y, curve);
}

void PlotView::AddData(double x[], double y[])
{
    plotcontroller->addData(x, y);
}

// response to user add action
void PlotView::AddCurve(std::string cur_name)
{
    plotcontroller->addCurve(cur_name);
}

void PlotView::SetCurveState(std::string cur_name, bool state)
{
    if(state == true)
        this->showCurve(cur_name);
    else this->hideCurve(cur_name);
}
